//
//  LFComposeViewController.swift
//  SDAutoWeibo
//
//  Created by 刘健 on 16/3/31.
//  Copyright © 2016年 Clemmie. All rights reserved.
//

import UIKit

class LFComposeViewController: UIViewController {
    
    //MARK: --  生命周期
    override func viewDidAppear(animated: Bool) {
        textView.becomeFirstResponder()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.lightGrayColor()
        
        setupNavbarItem()
        settingNavTitle()
        prepareUI()
        prepareToolBar()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillChange:"), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    //移除通知
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //MARK: -- 通知监听键盘
    func keyboardWillChange(noti:NSNotification) {
        //        LFPrint(msg: "\(noti.userInfo)")
        
        /**
        keyboardDidChange: Optional([UIKeyboardFrameBeginUserInfoKey: NSRect: {{0, 1236}, {414, 236}}, UIKeyboardCenterEndUserInfoKey: NSPoint: {207, 618}, UIKeyboardBoundsUserInfoKey: NSRect: {{0, 0}, {414, 236}}, UIKeyboardFrameEndUserInfoKey: NSRect: {{0, 500}, {414, 236}}, UIKeyboardAnimationDurationUserInfoKey: 0.4, UIKeyboardCenterBeginUserInfoKey: NSPoint: {207, 1354}, UIKeyboardAnimationCurveUserInfoKey: 7, UIKeyboardIsLocalUserInfoKey: 1])
        */
        
        //动画时间
        let animationTime = noti.userInfo!["UIKeyboardAnimationDurationUserInfoKey"] as? NSTimeInterval
        
        //获取keyboard frame
        let kbFrame = noti.userInfo!["UIKeyboardFrameEndUserInfoKey"]?.CGRectValue ?? CGRectZero
        
        //计算toolbar 的偏离值
        
        let hightMargin = -(UIScreen.mainScreen().bounds.height - kbFrame!.origin.y)
        
        //更新约束
        toolBar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view).offset(hightMargin)
        }
        
        //刷新界面
        UIView.animateWithDuration(animationTime!) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    //MARK: -- 布局UI控件
    private func prepareUI() {
        
        view.addSubview(textView)
        textView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(view)
        }
        
        let pView = pictVC.view
        view.addSubview(pView)
        
        //当一个子view 是另外一个控制器的view的时候，那么控制器也要是父子关系
        self.addChildViewController(pictVC)
        
        pView.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.equalTo(view)
            make.height.equalTo(view).multipliedBy(0.6)
            
            //底部先偏移height*0.6
            make.bottom.equalTo(view).offset(UIScreen.mainScreen().bounds.height * 0.6)
        }
        
    }
    
    //MARK: -- 设置toolBar
    private func prepareToolBar() {
        
        view.addSubview(toolBar)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon"],
            ["imageName": "compose_add_background", "action": "add"]]
        
        //遍历 itemSettings
        
        //创建数组toolBar.item
        //为添加不为空
        toolBar.items = [UIBarButtonItem]()
        for dict in itemSettings {
            
            let imageName = dict["imageName"]
            let action = dict["action"]
            
            let item = UIBarButtonItem(imageName: imageName!, target: self, action: Selector(action!))
            
            toolBar.items?.append(item)
            
            //增加弹簧
            toolBar.items?.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        //去掉最后一个弹簧
        toolBar.items?.removeLast()
    }
    
    //MARK: -- toolBar点击事件
    func picture() {
        LFPrint(msg: "图片")
        
        pictVC.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view)
        }
        
        UIView.animateWithDuration(LFRefreshAnimationTime) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    func trend() {
        LFPrint(msg: "#")
    }
    
    func mention() {
        LFPrint(msg:"@")
    }
    func emoticon() {
        LFPrint(msg: "emoticon")
    }
    func add() {
        LFPrint(msg: "add")
    }
    
    //MARK: -- 设置title
    private func settingNavTitle() {
        //设置标题
        let  titleName = "发微博"
        
        //获取
        let  userName =  LFGlobalUserAccountsViewModel.sharedUserAccounts.userAccounts?.screen_name
        
        //        LFPrint(msg: "\(userName)")
        
        let text = titleName + "\n" + userName!
        
        let label = UILabel()
        label.textAlignment = NSTextAlignment.Center
        label.font = UIFont.systemFontOfSize(16)
        label.numberOfLines = 0
        label.textColor = UIColor.blackColor()
        
        let dict = [NSForegroundColorAttributeName : UIColor.lightGrayColor(),NSFontAttributeName : UIFont.systemFontOfSize(11)]
        
        //获取要设置的文本范围
        let userNameRange = (text as NSString).rangeOfString(userName!)
        
        let attr = NSMutableAttributedString(string: text)
        
        attr.addAttributes(dict, range: userNameRange)
        
        label.attributedText = attr
        
        label.sizeToFit()
        
        if (userName != nil) {
            navigationItem.titleView = label
        }else {
            navigationItem.title = titleName
        }
    }
    
    //MARK: -- 增加2个按钮
    private func setupNavbarItem() {
        //增加导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickCancle")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "didClickSend")
        
        navigationItem.rightBarButtonItem?.enabled = false
    }
    
    //按钮点击事件
    @objc private func didClickCancle() {
        //取消第一响应者,键盘第一时间移除
        textView.resignFirstResponder()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func didClickSend() {
        LFPrint(msg:"发送")
    }
    
    //MARK: -- 懒加载
    //输入文本textView
    private lazy var textView :LFPlaceholderTextView = {
        let text = LFPlaceholderTextView()
        text.font = UIFont.systemFontOfSize(16)
        text.backgroundColor = UIColor.lightGrayColor()
        
        text.placeholderText = "分享微博..."
        
        text.alwaysBounceVertical = true
        //拖动键盘隐藏
        text.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        //代理
        text.delegate = self
        
        return text
    }()
    
    //toolBar
    private lazy var toolBar: UIToolbar = UIToolbar()
    
    //pictVC
    private lazy var pictVC: LFPitureViewController = LFPitureViewController()
}

//MARK: --LFPlaceholderTextView代理
extension LFComposeViewController :UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        //有文字就可以用
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
    }
}
